#include "D3dRender.h"

D3DRender::D3DRender()
	:m_pD3D(NULL), m_pD3DDevice(NULL)
{

}

D3DRender::~D3DRender()
{
	release();
}

void D3DRender::release()
{
	if(m_pD3DDevice != NULL) 
	{
		m_pD3DDevice->Release();
		m_pD3DDevice = NULL;
	}

	if(m_pD3D != NULL) 
	{
		m_pD3D->Release();
		m_pD3D = NULL;
	}
}

bool D3DRender::initializeD3d(HWND hWnd, bool fullScreen)
{
	if(m_pD3DDevice || m_pD3D)
		release();

	D3DDISPLAYMODE displayMode;
	// Create the D3D object.
	m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
	if(m_pD3D == NULL) return false;

	// Get the desktop display mode.
	if(FAILED(m_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode)))
		return false;

	// Set up the structure used to create the D3DDevice
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));
	if(fullScreen)
	{
		d3dpp.Windowed = FALSE;
		d3dpp.BackBufferWidth = 640;
		d3dpp.BackBufferHeight = 480;
	}
	else
		d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = displayMode.Format;

	// Create the D3DDevice
	if(FAILED(m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &m_pD3DDevice)))
	{
		return false;
	}
	return true;
}

void D3DRender::render()
{
	// Clear the backbuffer.
	m_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
	// Begin the scene. Start rendering.
	m_pD3DDevice->BeginScene();
	// End the scene. Stop rendering.
	m_pD3DDevice->EndScene();
	// Display the scene.
	m_pD3DDevice->Present(NULL, NULL, NULL, NULL);
}